<?php
class ControllerProductSpecial extends Controller {
	var $error = array();

	function index() {
		$response =& $this->locator->get('response');
		$language =& $this->locator->get('language');
		$template =& $this->locator->get('template'); 
		$module   =& $this->locator->get('module');
 
		$language->load('controller/product_special.php');

		$template->set('title', $language->get('heading_title'));

		$template->set('content', $this->getList());
		
		$template->set($module->fetch());

		$response->set($template->fetch('layout.tpl'));
	}

	function insert() {
		$request  =& $this->locator->get('request');
		$response =& $this->locator->get('response');
		$database =& $this->locator->get('database');
		$url      =& $this->locator->get('url');
		$language =& $this->locator->get('language');
		$template =& $this->locator->get('template');
		$session  =& $this->locator->get('session');
		$module   =& $this->locator->get('module');
		$cache    =& $this->locator->get('cache');

		$language->load('controller/product_special.php');

		$template->set('title', $language->get('heading_title'));

		if ($request->isPost() && $request->has('discount', 'post') && $this->validateForm()) {
			
			// Loop through selected products and replace all existing sales since you can only have one sale per product
			foreach ($request->gethtml('product', 'post', array()) as $product_id) {
				$database->query("delete from product_special where product_id = '" . (int)$product_id . "'");
				$sql = "insert into product_special set product_id = '?', prefix = '?', discount = '?', date_start = '?', date_end = '?', status = '?' ";
				$database->query($database->parse($sql, $product_id, $request->get('prefix', 'post'), $request->get('discount', 'post'), date('Y-m-d', strtotime($request->gethtml('date_start_year', 'post') . '/' . $request->gethtml('date_start_month', 'post') . '/' . $request->gethtml('date_start_day', 'post'))), date('Y-m-d', strtotime($request->gethtml('date_end_year', 'post') . '/' . $request->gethtml('date_end_month', 'post') . '/' . $request->gethtml('date_end_day', 'post'))), $request->gethtml('status', 'post')));
			}

			$session->set('message', $language->get('text_message'));
			
			$response->redirect($url->ssl('product_special'));
		}

		$template->set('content', $this->getForm());

		$template->set($module->fetch());

		$response->set($template->fetch('layout.tpl'));
	}

	function update() {
		$request  =& $this->locator->get('request');
		$response =& $this->locator->get('response');
		$database =& $this->locator->get('database');
		$url      =& $this->locator->get('url');
		$language =& $this->locator->get('language');
		$template =& $this->locator->get('template');
		$session  =& $this->locator->get('session');
		$module   =& $this->locator->get('module');
		$cache    =& $this->locator->get('cache');

		$language->load('controller/product_special.php');

		$template->set('title', $language->get('heading_title'));

		if ($request->isPost() && $request->has('discount', 'post') && $this->validateForm()) {
			
			// Delete the current special as it might have been replaced with multiple sales
			$database->query("delete from product_special where special_id = '" . (int)$request->get('special_id') . "'");
		
			// Loop through selected products and replace all existing sales since you can only have one sale per product
			foreach ($request->gethtml('product', 'post', array()) as $product_id) {
				$database->query("delete from product_special where product_id = '" . (int)$product_id . "'");
				$sql = "insert into product_special set product_id = '?', prefix = '?', discount = '?', date_start = '?', date_end = '?', status = '?' ";
				$database->query($database->parse($sql, $product_id, $request->get('prefix', 'post'), $request->get('discount', 'post'), date('Y-m-d', strtotime($request->gethtml('date_start_year', 'post') . '/' . $request->gethtml('date_start_month', 'post') . '/' . $request->gethtml('date_start_day', 'post'))), date('Y-m-d', strtotime($request->gethtml('date_end_year', 'post') . '/' . $request->gethtml('date_end_month', 'post') . '/' . $request->gethtml('date_end_day', 'post'))), $request->gethtml('status', 'post')));
			}
			
			$session->set('message', $language->get('text_message'));
			
			$response->redirect($url->ssl('product_special'));
		}

		$template->set('content', $this->getForm());

		$template->set($module->fetch());

		$response->set($template->fetch('layout.tpl'));
	}

	function delete() {
		$request  =& $this->locator->get('request');
		$response =& $this->locator->get('response');
		$database =& $this->locator->get('database');
		$url      =& $this->locator->get('url');
		$language =& $this->locator->get('language');
		$template =& $this->locator->get('template');
		$session  =& $this->locator->get('session');
		$module   =& $this->locator->get('module');
		$cache    =& $this->locator->get('cache');

		$language->load('controller/product_special.php');

		$template->set('title', $language->get('heading_title'));

		if (($request->get('special_id')) && ($this->validateDelete())) {
			$database->query("delete from product_special where special_id = '" . (int)$request->get('special_id') . "'");
 
			$session->set('message', $language->get('text_message'));
			
			$response->redirect($url->ssl('product_special'));
		}

		$template->set('content', $this->getList());

		$template->set($module->fetch());

		$response->set($template->fetch('layout.tpl'));
	}

	function getList() {
		$request  =& $this->locator->get('request');
		$database =& $this->locator->get('database');
		$config   =& $this->locator->get('config');
		$currency =& $this->locator->get('currency');
		$url      =& $this->locator->get('url');
		$language =& $this->locator->get('language');
		$session  =& $this->locator->get('session');
		$template =& $this->locator->get('template');

		$cols = array();

		$cols[] = array(
			'name'  => $language->get('column_product'),
			'sort'  => 'product',
			'align' => 'left'
		);
		
			$cols[] = array(
			'name'  => $language->get('column_regprice'),
			'sort'  => 'price',
			'align' => 'left'
		);
		
		$cols[] = array(
			'name'  => $language->get('column_prefix'),
			'sort'  => 'prefix',
			'align' => 'center'
		);
		
		$cols[] = array(
			'name'  => $language->get('column_discount'),
			'sort'  => 'discount',
			'align' => 'center'
		);
		
		$cols[] = array(
			'name'  => $language->get('column_specprice'),
			'sort'  => 'price',
			'align' => 'center'
		);
		
		$cols[] = array(
			'name'  => $language->get('column_date_start'),
			'sort'  => 'date_start',
			'align' => 'center'
		);

		$cols[] = array(
			'name'  => $language->get('column_date_end'),
			'sort'  => 'date_end',
			'align' => 'center'
		);

    	$cols[] = array(
      		'name'  => $language->get('column_action'),
      		'align' => 'right'
    	);
		
		if (!$session->get('special.search')) {
			$sql = "select * from product_special";
		} else {
			$sql = "select * from product_special where product_id like '?' or discount like '?'";
		}

		$sort = array(
			'special_id',
			'product_id',
			'prefix',
			'discount',
			'date_start',
			'date_end'			
		);

		if (in_array($session->get('special.sort'), $sort)) {
			$sql .= " order by " . $session->get('special.sort') . " " . (($session->get('special.order') == 'desc') ? 'desc' : 'asc');
		} else {
			$sql .= " order by special_id asc";
		}

		$results = $database->getRows($database->splitQuery($database->parse($sql, '%' . $session->get('special.search') . '%','%' . $session->get('special.search') . '%'), $session->get('special.page'), $config->get('config_max_rows')));

		$rows = array();

		foreach ($results as $result) {
			$cell = array();

			$res = $database->getRow("select p.price, pd.name from product p left join product_description pd on (p.product_id = pd.product_id) where p.product_id = '" . (int)$result['product_id'] . "'");
			$cell[] = array(
				'value' => $res['name'],
				'align' => 'left'
			);
			
			$cell[] = array(
				'value' => ($res['price'] ? $currency->format($res['price']) : 0),
				'align' => 'left'
			);
			
			$cell[] = array(
				'value' => $result['prefix'],
				'align' => 'center'
			);
			
			$cell[] = array(
				'value' => $result['discount'],
				'align' => 'center'
			);
			
			$spec = $database->getRow("select prefix, discount from product_special where product_id = '" . (int)$result['product_id'] . "'");
			if ($spec['prefix'] == '%') {
				$special_price = $res['price'] - ($res['price'] * ($spec['discount']/100));
			} elseif ($spec['prefix'] == '-') {
				$special_price = $res['price'] - $spec['discount'];
			} else {
				$special_price = $spec['discount'];
			}
			
			$cell[] = array(
				'value' => '<span style="font-weight: bold; color: #ff0000;">' . ($special_price ? $currency->format($special_price) : 0) . '</span>',
				'align' => 'center'
			);
			
			
			$cell[] = array(
				'value' => $result['date_start'],
				'align' => 'center'
			);
			
			$cell[] = array(
				'value' => $result['date_end'],
				'align' => 'center'
			);
			
			$action = array();
      		
			$action[] = array(
        		'icon' => 'update.png',
				'text' => $language->get('button_update'),
				'href' => $url->ssl('product_special', 'update', array('special_id' => $result['special_id']))
      		);
      		
      		$action[] = array(
        		'icon' => ($result['status'] ? 'enabled.png' : 'disabled.png'),
				'text' => $language->get('button_status'),
				'href' => $url->ssl('product_special', 'toggleStatus', array('special_id' => $result['special_id']))
      		);
						
			$action[] = array(
        		'icon' => 'delete.png',
				'text' => $language->get('button_delete'),
				'href' => $url->ssl('product_special', 'delete', array('special_id' => $result['special_id']))
      		);

      		$cell[] = array(
        		'action' => $action,
        		'align'  => 'right'
      		);
			
			$rows[] = array('cell' => $cell);
		}

		$view = $this->locator->create('template');

		$view->set('tpl', $template);

		$view->set('heading_title', $language->get('heading_title'));
		$view->set('heading_description', $language->get('heading_description'));

		$view->set('text_results', $language->get('text_results', $database->getFrom(), $database->getTo(), $database->getTotal()));

		$view->set('entry_page', $language->get('entry_page'));
		$view->set('entry_search', $language->get('entry_search'));

		
		$view->set('button_insert', $language->get('button_insert'));
		$view->set('button_update', $language->get('button_update'));
		$view->set('button_delete', $language->get('button_delete'));

		$view->set('error', @$this->error['message']);

		$view->set('message', $session->get('message'));
		
		$session->delete('message');
		
		$view->set('action', $url->ssl('product_special', 'page'));
 
		$view->set('search', $session->get('special.search'));
		$view->set('sort', $session->get('special.sort'));
		$view->set('order', $session->get('special.order'));
		$view->set('page', $session->get('special.page'));

		$view->set('cols', $cols);
		$view->set('rows', $rows);

		$view->set('list', $url->ssl('product_special'));

		$view->set('insert', $url->ssl('product_special', 'insert'));

		$page_data = array();

		for ($i = 1; $i <= $database->getPages(); $i++) {
			$page_data[] = array(
				'text'  => $language->get('text_pages', $i, $database->getPages()),
				'value' => $i
			);
		}

		$view->set('pages', $page_data);

		return $view->fetch('content/list.tpl');
	}

	function getForm() {
		$request  =& $this->locator->get('request');
		$database =& $this->locator->get('database');
		$config   =& $this->locator->get('config');
		$currency =& $this->locator->get('currency');
		$url      =& $this->locator->get('url');
		$language =& $this->locator->get('language');
		$template =& $this->locator->get('template');
   
    	$view = $this->locator->create('template');

		$view->set('tpl', $template);

    	$view->set('heading_title', $language->get('heading_title'));
    	$view->set('heading_description', $language->get('heading_description'));

    	$view->set('text_enabled', $language->get('text_enabled'));
    	$view->set('text_disabled', $language->get('text_disabled'));
    	$view->set('text_yes', $language->get('text_yes'));
    	$view->set('text_no', $language->get('text_no'));
    	$view->set('text_percent', $language->get('text_percent'));
    	$view->set('text_minus', $language->get('text_minus'));
    	$view->set('text_equal', $language->get('text_equal'));
		
		$view->set('entry_discount', $language->get('entry_discount'));
    	$view->set('entry_prefix', $language->get('entry_prefix'));
    	$view->set('entry_date_start', $language->get('entry_date_start'));
    	$view->set('entry_date_end', $language->get('entry_date_end'));
		$view->set('entry_product', $language->get('entry_product'));
		$view->set('entry_status', $language->get('entry_status'));

    	$view->set('button_save', $language->get('button_save'));
    	$view->set('button_cancel', $language->get('button_cancel'));

    	$view->set('tab_general', $language->get('tab_general'));
    	$view->set('tab_data', $language->get('tab_data'));

    	$view->set('error', @$this->error['message']);
    	$view->set('error_discount', @$this->error['discount']);
    	$view->set('error_date_start', @$this->error['date_start']);
		$view->set('error_date_end', @$this->error['date_end']);
		
    	$view->set('action', $url->ssl('product_special', $request->gethtml('action'), array('special_id' => $request->gethtml('special_id'))));
    
    	$view->set('cancel', $url->ssl('product_special'));

    	if (($request->gethtml('special_id')) && (!$request->isPost())) {
      		$special_info = $database->getRow("select distinct * from product_special where special_id = '" . (int)$request->gethtml('special_id') . "'");
    	}

    	if ($request->has('discount', 'post')) {
      		$view->set('discount', $request->gethtml('discount', 'post'));
    	} else {
      		$view->set('discount', @$special_info['discount']);
    	}
				
    	if ($request->has('prefix', 'post')) {
      		$view->set('prefix', $request->gethtml('prefix', 'post'));
    	} else {
      		$view->set('prefix', @$special_info['prefix']);
    	}

    	$month_data = array();

    	$month_data[] = array(
      		'value' => '01',
      		'text'  => $language->get('text_january')
    	);

    	$month_data[] = array(
      		'value' => '02',
      		'text'  => $language->get('text_february')
    	);

    	$month_data[] = array(
      		'value' => '03',
      		'text'  => $language->get('text_march')
    	);

    	$month_data[] = array(
      		'value' => '04',
      		'text'  => $language->get('text_april')
    	);

    	$month_data[] = array(
      		'value' => '05',
      		'text'  => $language->get('text_may')
    	);

    	$month_data[] = array(
      		'value' => '06',
      		'text'  => $language->get('text_june')
    	);

    	$month_data[] = array(
      		'value' => '07',
      		'text'  => $language->get('text_july')
    	);

    	$month_data[] = array(
      		'value' => '08',
      		'text'  => $language->get('text_august')
    	);

    	$month_data[] = array(
      		'value' => '09',
      		'text'  => $language->get('text_september')
    	);

    	$month_data[] = array(
      		'value' => '10',
      		'text'  => $language->get('text_october')
    	);

    	$month_data[] = array(
      		'value' => '11',
      		'text'  => $language->get('text_november')
    	);

    	$month_data[] = array(
      		'value' => '12',
      		'text'  => $language->get('text_december')
    	);

    	$view->set('months', $month_data);
      	
		if (isset($special_info['date_start'])) {
        	$date = explode('/', date('d/m/Y', strtotime($special_info['date_start'])));
      	} else {
        	$date = explode('/', date('d/m/Y', time()));
      	}
			
    	if ($request->has('date_start_day', 'post')) {
      		$view->set('date_start_day', $request->gethtml('date_start_day', 'post'));
    	} else {
      		$view->set('date_start_day', $date[0]);
    	}			
			
    	if ($request->has('date_start_month', 'post')) {
      		$view->set('date_start_month', $request->gethtml('date_start_month', 'post'));
    	} else {
      		$view->set('date_start_month', $date[1]);
    	}

    	if ($request->has('date_start_year', 'post')) {
      		$view->set('date_start_year', $request->gethtml('date_start_year', 'post'));
    	} else {
      		$view->set('date_start_year', $date[2]);
    	}					

		if (isset($special_info['date_end'])) {
        	$date = explode('/', date('d/m/Y', strtotime($special_info['date_end'])));
      	} else {
        	$date = explode('/', date('d/m/Y', time()));
      	}
			
    	if ($request->has('date_end_day', 'post')) {
      		$view->set('date_end_day', $request->gethtml('date_end_day', 'post'));
    	} else {
      		$view->set('date_end_day', $date[0]);
    	}			
			
    	if ($request->has('date_end_month', 'post')) {
      		$view->set('date_end_month', $request->gethtml('date_end_month', 'post'));
    	} else {
      		$view->set('date_end_month', $date[1] + 1);
    	}

    	if ($request->has('date_end_year', 'post')) {
      		$view->set('date_end_year', $request->gethtml('date_end_year', 'post'));
    	} else {
      		$view->set('date_end_year', $date[2]);
		}

    	$product_data = array();

    	$results = $database->cache('product', "select * from product p left join product_description pd on (p.product_id = pd.product_id) where pd.language_id = '" . (int)$language->getId() . "' order by pd.name");
 
    	foreach ($results as $result) {
			if (($request->gethtml('special_id')) && (!$request->isPost())) {  
	  			$special_product_info = $database->getRow("select * from product_special where special_id = '" . (int)$request->gethtml('special_id') . "' and product_id = '" . (int)$result['product_id'] . "'");
			}

      		$product_data[] = array(
        		'product_id' => $result['product_id'],
        		'name'       => $result['name'],
        		'regprice'   => $currency->format($result['price']),
        		'special_id'  => (isset($special_product_info) ? $special_product_info : in_array($result['product_id'], $request->gethtml('product', 'post', array())))
      		);
    	}

    	$view->set('products', $product_data);

    	if ($request->has('status', 'post')) {
      		$view->set('status', $request->gethtml('status', 'post'));
    	} elseif (isset($special_info['status'])) {
      		$view->set('status', @$special_info['status']);
    	} else {
		 	$view->set('status', '1');
		}
 		return $view->fetch('content/product_special.tpl');
  	}

	function validateForm() {
		$request  =& $this->locator->get('request');
		$language =& $this->locator->get('language');
		$user     =& $this->locator->get('user');
        $validate =& $this->locator->get('validate');

		if (!$user->hasPermission('modify', 'special')) {
			$this->error['message'] = $language->get('error_permission');
		}

		if (!$validate->strlen($request->gethtml('discount', 'post'),1,15)) {
            $this->error['discount'] = $language->get('error_discount');
        }
		
		if (!$request->gethtml('date_start_month', 'post') || !$request->gethtml('date_start_day', 'post') || !$request->gethtml('date_start_year', 'post')) {
	  		$this->error['date_start'] = $language->get('error_date_start');
		} elseif (!checkdate($request->gethtml('date_start_month', 'post'), $request->gethtml('date_start_day', 'post'), $request->gethtml('date_start_year', 'post'))) {
	  		$this->error['date_start'] = $language->get('error_date_start');
		}
		
		if (!$request->gethtml('date_end_month', 'post') || !$request->gethtml('date_end_day', 'post') || !$request->gethtml('date_end_year', 'post')) {
	  		$this->error['date_end'] = $language->get('error_date_end');
		} elseif (!checkdate($request->gethtml('date_end_month', 'post'), $request->gethtml('date_end_day', 'post'), $request->gethtml('date_end_year', 'post'))) {
	  		$this->error['date_end'] = $language->get('error_date_end');
		}
		
		if (!$this->error) {
			return TRUE;
		} else {
			return FALSE;
		}
	}

	function validateDelete() {
		$user     =& $this->locator->get('user');
		$language =& $this->locator->get('language');

		if (!$user->hasPermission('modify', 'special')) {
			$this->error['message'] = $language->get('error_permission');
		}

		if (!$this->error) {
			return TRUE;
		} else {
			return FALSE;
		}
	}

	function page() {
		$request  =& $this->locator->get('request');
		$response =& $this->locator->get('response');
		$url      =& $this->locator->get('url');
		$session  =& $this->locator->get('session');

		if ($request->has('search', 'post')) {
			$session->set('special.search', $request->gethtml('search', 'post'));
		}

		if (($request->has('page', 'post')) || ($request->has('search', 'post'))) {
			$session->set('special.page', $request->gethtml('page', 'post'));
		}

		if ($request->has('sort', 'post')) {
			$session->set('special.order', (($session->get('special.sort') == $request->gethtml('sort', 'post')) && ($session->get('special.order') == 'asc')) ? 'desc' : 'asc');
		}

		if ($request->has('sort', 'post')) {
			$session->set('special.sort', $request->gethtml('sort', 'post'));
		}

		$response->redirect($url->ssl('product_special'));
	}

	function toggleStatus() {
		$request  =& $this->locator->get('request');
		$response =& $this->locator->get('response');
		$database =& $this->locator->get('database');
		$url      =& $this->locator->get('url');
		$language =& $this->locator->get('language');
		$template =& $this->locator->get('template');
		$session  =& $this->locator->get('session');
		$module   =& $this->locator->get('module');
		$cache    =& $this->locator->get('cache');
		
		$language->load('controller/product_special.php');
		
		$result = $database->getRow("select status from product_special where `special_id` = '" . $request->gethtml('special_id') . "'"); 
		$sql = "update product_special set status = '?' where special_id = '?'";
      	$database->query($database->parse($sql, ($result['status'] == 1) ? 0 : 1, $request->gethtml('special_id')));
	  		
		$session->set('message', $language->get('text_status_message'));
		$response->redirect($url->ssl('product_special'));     		
		
	}
	
}
?>
